package cn.iocoder.yudao.module.ai.controller.admin.dataset;

import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.dict.core.DictFrameworkUtils;
import cn.iocoder.yudao.framework.exception.BusinessException;
import cn.iocoder.yudao.module.ai.constant.DicConstant;
import cn.iocoder.yudao.module.ai.controller.admin.datasetmark.vo.DatasetMarkRespVO;
import cn.iocoder.yudao.module.ai.controller.admin.datasetreleasefile.vo.DatasetReleaseFilePageReqVO;
import cn.iocoder.yudao.module.ai.controller.admin.datasetreleasefile.vo.DatasetReleaseFileRespVO;
import cn.iocoder.yudao.module.ai.controller.admin.datasetversion.vo.DatasetQualityTaskSaveReqVO;
import cn.iocoder.yudao.module.ai.controller.admin.datasetversion.vo.DatasetVersionSaveReqVO;
import cn.iocoder.yudao.module.ai.dal.dataobject.datasetmark.DatasetLableFilecountDO;
import cn.iocoder.yudao.module.ai.dal.dataobject.datasetmark.DatasetMarkDO;
import cn.iocoder.yudao.module.ai.dal.dataobject.datasetreleasefile.DatasetReleaseFileDO;
import cn.iocoder.yudao.module.ai.dal.mysql.dataset.DatasetMapper;
import cn.iocoder.yudao.module.ai.service.datasetmark.DatasetMarkService;
import cn.iocoder.yudao.module.ai.service.datasetreleasefile.DatasetReleaseFileService;
import cn.iocoder.yudao.module.ai.service.datasetversion.DatasetVersionService;
import cn.iocoder.yudao.module.infra.util.StringUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.module.ai.controller.admin.dataset.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.dataset.DatasetDO;
import cn.iocoder.yudao.module.ai.service.dataset.DatasetService;

@Tag(name = "管理后台 - 数据集管理")
@RestController
@RequestMapping("/ai/dataset")
@Validated
@Slf4j
public class DatasetController {

    @Resource
    private DatasetService datasetService;
    @Resource
    private DatasetMapper datasetMapper;
    @Resource
    private DatasetReleaseFileService datasetReleaseFileService;
    @Resource
    private DatasetMarkService datasetMarkService;
    @Resource
    private DatasetVersionService datasetVersionService;
    @Resource
    private AdminUserApi adminUserApi ;
    /**
     * 应用名
     */
    @Value("${material.access-path}")
    private String materialFilePrePath;

    @GetMapping("/getnewname")
    @Operation(summary = "获得数据集新名称")
    @PreAuthorize("@ss.hasPermission('aai:dataset:create')")
    public CommonResult<String> getNewName() {
        String s = "data_"+RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER_LOWER, 6);
        return success(s);
    }

    @PostMapping("/create")
    @Operation(summary = "创建数据集管理")
    @PreAuthorize("@ss.hasPermission('ai:dataset:create')")
    public CommonResult<Long> createDataset(DatasetSaveReqVO createReqVO) {
        if(null != createReqVO.getId()){
            return  error(CommonResult.error(500,"创建不能填写编号"));
        }
        checkLabelInfo(createReqVO.getLabelInfo());
        return success(datasetService.saveDataset(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "修改数据集管理")
    @PreAuthorize("@ss.hasPermission('ai:dataset:create')")
    public CommonResult<Boolean> update(@RequestBody  DatasetUpdateReqVO saveReqVO) {
        if(null == saveReqVO.getId()){
            return  error(CommonResult.error(500,"编号不能为空"));
        }
        try{
            DatasetDO dataset = datasetService.getDataset(saveReqVO.getId());
            if(null == dataset){
                return  error(CommonResult.error(500,"数据集不存在"));
            }
            if(DicConstant.dataSet_quality_status_ing.equals(dataset.getQualityStatus())){
                throw new BusinessException("质检过程中不能更新数据集");
            }
        }catch (Exception e){
            return  error(CommonResult.error(500,"数据集不存在"));
        }
        checkLabelInfo(saveReqVO.getLabelInfo());
        datasetService.updateDataset(saveReqVO);
        return success(Boolean.TRUE);
    }

    /**
     * 验证标签信息格式
     * @param labelInfo
     */
    private void checkLabelInfo(String labelInfo) {
        if(StringUtils.isNotBlank(labelInfo)){
            try {
                List<Map> list = JSONArray.parseArray(labelInfo, Map.class);
                if(CollectionUtils.isNotEmpty(list)){
                    for (int i = 0; i < list.size(); i++) {
                        if(!list.get(i).containsKey("labelId") || !list.get(i).containsKey("labelName") || !list.get(i).containsKey("color")){
                            throw new BusinessException( "标签格式错误");
                        }
                    }
                }
            } catch (Exception e) {
                throw new BusinessException( "标签格式错误");
            }
        }
    }

    @PutMapping("/uploadfile")
    @Operation(summary = "上传文件")
    @PreAuthorize("@ss.hasPermission('ai:dataset:update')")
    public CommonResult<Boolean> uploadFile(DatasetUploadFileReqVO uploadFileReqVO) {
        if(null == uploadFileReqVO.getId()){
            return  error(CommonResult.error(500,"编号不能为空"));
        }
        try{
            DatasetDO dataset = datasetService.getDataset(uploadFileReqVO.getId());
            if(null == dataset){
                return  error(CommonResult.error(500,"数据集不存在"));
            }
            if(DicConstant.dataSet_quality_status_ing.equals(dataset.getQualityStatus())){
                throw new BusinessException("质检过程中不能更新数据集");
            }
        }catch (Exception e){
            return  error(CommonResult.error(500,"数据集不存在"));
        }
        datasetService.uploadFile(uploadFileReqVO);
        return success(true);
    }

    @PutMapping("/publish")
    @Operation(summary = "发布版本")
    @PreAuthorize("@ss.hasPermission('ai:dataset:update')")
    public CommonResult<Boolean> publish(@RequestBody DatasetVersionSaveReqVO datasetVersionSaveReqVO) {
        datasetService.publish(datasetVersionSaveReqVO);
        return success(true);
    }

    @PutMapping("/createqualitytask")
    @Operation(summary = "创建质检任务")
    @PreAuthorize("@ss.hasPermission('ai:dataset:update')")
    public CommonResult<Boolean> createQualityTask(@RequestBody DatasetQualityTaskSaveReqVO datasetQualityTaskSaveReqVO) {
        datasetService.createQualityTask(datasetQualityTaskSaveReqVO);
        return success(true);
    }

    @PutMapping("/updatefilequalitystatus")
    @Operation(summary = "更新文件质检状态")
    @PreAuthorize("@ss.hasPermission('ai:dataset:update')")
    public CommonResult<Boolean> updateFileQuality(DatasetFileQualityReqVO datasetFileQualityReqVO) {

        DatasetReleaseFileDO datasetReleaseFile =
                datasetReleaseFileService.getDatasetReleaseFile(datasetFileQualityReqVO.getOriginalFileId());
        if(null == datasetReleaseFile){
            throw new BusinessException("数据不存在");
        }
        datasetService.updateFileQuality(datasetFileQualityReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除数据集管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:dataset:delete')")
    public CommonResult<Boolean> deleteDataset(@RequestParam("id") Long id) {
        datasetService.deleteDataset(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得数据集管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:dataset:query')")
    public CommonResult<DatasetRespVO> getDataset(@RequestParam("id") Long id,HttpServletRequest request) {
        DatasetDO dataset = datasetService.getDataset(id);
        if(null == dataset){
            return  error(CommonResult.error(500,"数据集不存在"));
        }
        DatasetRespVO bean = BeanUtils.toBean(dataset, DatasetRespVO.class);
        bean.setVersionList(datasetVersionService.getVersionListByDatasetId(id));
        // bean.setOriginalFileList(datasetReleaseFileService.getOriginalFileListByDatasetId(id));
        bean.setUrl(getUrl(request,bean.getFileUploadPath()));
        bean.setFileTypeName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_mark_file_type, bean.getFileType()));
        bean.setSourceTypeName(DictFrameworkUtils.getDictDataLabel(DicConstant.materialLibraryType, bean.getSourceType()));
        bean.setIndustryName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_Industry_affiliation, bean.getIndustryId()));
        bean.setIndustry2Name(DictFrameworkUtils.getDictDataLabel(DicConstant.key_model_broad_category, bean.getIndustryId2()));
        bean.setIndustry3Name(DictFrameworkUtils.getDictDataLabel(DicConstant.key_model_subclass, bean.getIndustryId3()));
        bean.setSenceTypeName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_mark_biz_type, bean.getSenceType()));
        bean.setQualityStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_quality_status, bean.getQualityStatus()));
        bean.setPublishStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_publish_status, bean.getPublishStatus()));
        bean.setMarkStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_mark_status, bean.getMarkStatus()));
        Map<Long, DatasetReleaseFileDO> firstFileMap = datasetService.getFirstFileMap(Lists.newArrayList(bean.getId()));
        bean.setFirstFileUrl(getUrl(request,null==firstFileMap.get(bean.getId())?null:firstFileMap.get(bean.getId()).getFileUploadPath()));
        bean.setUrl(getUrl(request,bean.getFileUploadPath()));
        try {
            List<String> markFileClassesList = JSONArray.parseArray(bean.getMarkFileClasses(), String.class);
            List<Map> labelInfoList = JSONArray.parseArray(bean.getLabelInfo(), Map.class);
            bean.setMarkFileClassesList(markFileClassesList);
            // 统计标签文件数量
            List<DatasetLableFilecountDO> datasetLableFilecountDOS = datasetMarkService.groupFileCountByLabelId(bean.getId());
            // 处理标签名称
            if(CollectionUtils.isNotEmpty(datasetLableFilecountDOS)
                    && CollectionUtils.isNotEmpty(markFileClassesList)
                    && CollectionUtils.isNotEmpty(labelInfoList)){
                for (DatasetLableFilecountDO datasetLableFilecountDO : datasetLableFilecountDOS) {
                    if(markFileClassesList.size() > datasetLableFilecountDO.getLabelIndex()){
                        String labelName = markFileClassesList.get(datasetLableFilecountDO.getLabelIndex());
                        for (Map map : labelInfoList) {
                            if(map.containsKey("labelName") && map.get("labelName").equals(labelName)){
                                map.put("labelFileCount", datasetLableFilecountDO.getFileCount());
                                break;
                            }
                        }
                    }
                }
            }
            bean.setLabelInfoList(labelInfoList);
        } catch (Exception e) {
            //throw new RuntimeException(e);
        }
        // 设置创建者和上传者名称
        if(null != bean.getCreator()){
            AdminUserRespDTO user = adminUserApi.getUser(Long.parseLong(bean.getCreator()));
            if(null != user){
                bean.setCreatorName(user.getNickname());
                bean.setUploderName(user.getNickname());
            }
        }
// 太多了，暂时不用了。走下面的分页获取接口
//        if(CollectionUtils.isNotEmpty(bean.getOriginalFileList())){
//            // 查询所有标注文件
//            List<DatasetMarkDO> markListByDatasetId = datasetMarkService.getMarkListByDatasetId(bean.getId());
//            List<DatasetMarkRespVO> markRespVOList = BeanUtils.toBean(markListByDatasetId, DatasetMarkRespVO.class);
//            if(CollectionUtils.isNotEmpty(markRespVOList)){
//                setMarkLabelColor(markRespVOList,dataset);
//            }
//            // 查询解压原始文件信息
//            for (DatasetReleaseFileRespVO respVO : bean.getOriginalFileList()) {
//                respVO.setOriginalFileUrl(getUrl(request,respVO.getFileUploadPath()));
//                respVO.setMarkFileUrl(getUrl(request,respVO.getMarkFileUploadPath()));
//                respVO.setQualityStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_file_quality_status, respVO.getQualityStatus()));
//                // 设置标注文件信息
//                if(CollectionUtils.isNotEmpty(markRespVOList)){
//                    respVO.setDatasetMarkList(markRespVOList.stream().filter(mark -> mark.getMarkOriginalFileId().equals(respVO.getId())).collect(Collectors.toList()));
//                }
//            }
//        }
        return success(bean);
    }

//    @GetMapping("/getmarkbymarkfileid")
//    @Operation(summary = "根据标注文件编号获得文件标注信息")
//    @Parameter(name = "markFileId", description = "标注解压文件编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('ai:dataset:query')")
//    public CommonResult<List<DatasetMarkRespVO>> getDatasetMarkByMarkFileId(@RequestParam("markFileId") Long markFileId) {
//        List<DatasetMarkDO> markListByMarkFileId = datasetMarkService.getMarkListByMarkFileId(markFileId);
//        List<DatasetMarkRespVO> voList = BeanUtils.toBean(markListByMarkFileId, DatasetMarkRespVO.class);
//        if(CollectionUtils.isNotEmpty(voList)){
//            DatasetDO datasetDO = datasetMapper.selectById(voList.get(0).getDatasetId());
//            setMarkLabelColor(voList,datasetDO);
//        }
//        return success(voList);
//    }

    /**
     * 设置标注信息
     * @param voList
     */
    private void setMarkLabelColor(List<DatasetMarkRespVO> voList,DatasetDO dataset) {
        if(null == dataset){
            return;
        }
        if(CollectionUtils.isNotEmpty(voList)){
            for (DatasetMarkRespVO datasetMarkRespVO : voList) {
                if(StringUtils.isNotBlank(datasetMarkRespVO.getMarkContent())){
                    try {
                        List<String> strings = JSONArray.parseArray(datasetMarkRespVO.getMarkContent(), String.class);
                        List<Double[]> markList = new ArrayList<>();
                        if(CollectionUtils.isNotEmpty(strings)){
                            Double[] doubles = null;
                            for (int i = 0; i < strings.size(); i++) {
                                if(i%2 == 0){
                                    doubles = new Double[2];
                                    doubles[0] = Double.parseDouble(strings.get(i));
                                }
                                if(i%2 ==1){
                                    doubles[1] = Double.parseDouble(strings.get(i));
                                    markList.add(doubles);
                                }
                            }
                            // --如果剩余一个，也要放进去
                            if(strings.size() % 2 == 1){
                                markList.add(doubles);
                            }
                        }
                        datasetMarkRespVO.setMarkList(markList);
                    } catch (Exception e) {
                        log.warn("转化坐标出现异常；content="+datasetMarkRespVO.getMarkContent());
                        //throw new RuntimeException(e);
                    }
                }
            }
            if(StringUtils.isNotBlank(dataset.getMarkFileClasses())){
                try {
                    JSONArray labelNameArray = JSONArray.parseArray(dataset.getMarkFileClasses());
                    List<HashMap> labelInfoArray = null ;
                    try {
                        if(StringUtils.isNotBlank(dataset.getLabelInfo())){
                            labelInfoArray = JSONArray.parseArray(dataset.getLabelInfo(),HashMap.class);
                        }
                    } catch (Exception e) {
                        //throw new RuntimeException(e);
                        log.warn("获取标注文件类失败",e);
                    }
                    for (DatasetMarkRespVO respVO : voList) {
                        if(null != labelNameArray && labelNameArray.size() > respVO.getLabelIndex()){
                            respVO.setLabelName(labelNameArray.getString(respVO.getLabelIndex()));
                            if(null != labelInfoArray && labelInfoArray.size() > 0){
                                for (int i = 0; i < labelInfoArray.size(); i++) {
                                    if(respVO.getLabelName().equals(labelInfoArray.get(i).get("labelName"))){
                                        respVO.setLabelColor((String)labelInfoArray.get(i).get("color"));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                } catch (RuntimeException e) {
                    //throw new RuntimeException(e);
                    log.warn("获取标注文件类失败",e);
                }
            }
        }
    }

//    @GetMapping("/getmarkbyoriginalfileid")
//    @Operation(summary = "根据原始文件编号获得文件标注信息")
//    @Parameter(name = "originalFileId", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('ai:dataset:getmarkbyoriginalfileid')")
//    public CommonResult<List<DatasetMarkRespVO>> getDatasetMarkByOriginalFileId(@RequestParam("originalFileId") Long originalFileId) {
//        List<DatasetMarkDO> markList = datasetMarkService.getMarkListByOriginalFileId(originalFileId);
//        List<DatasetMarkRespVO> voList = BeanUtils.toBean(markList, DatasetMarkRespVO.class);
//        if(CollectionUtils.isNotEmpty(voList)){
//            DatasetDO datasetDO = datasetMapper.selectById(voList.get(0).getDatasetId());
//            setMarkLabelColor(voList,datasetDO);
//        }
//        return success(voList);
//    }

    @GetMapping("/getdatasetfilepage")
    @Operation(summary = "分页获得数据集文件")
    @PreAuthorize("@ss.hasPermission('ai:dataset:query')")
    public CommonResult<PageResult<DatasetReleaseFileRespVO>> getDatasetFilePage(@Valid DatasetFilePageReqVO datasetFilePageReqVO,HttpServletRequest request) {
        DatasetDO dataset = datasetService.getDataset(datasetFilePageReqVO.getDatasetId());
        if(null == dataset){
            return  error(CommonResult.error(500,"数据集不存在"));
        }
        DatasetReleaseFilePageReqVO pageReqVO = new DatasetReleaseFilePageReqVO();
        pageReqVO.setDatasetId(datasetFilePageReqVO.getDatasetId());
        pageReqVO.setFileBizType(DicConstant.dataSet_file_biz_type_original);
        pageReqVO.setPageNo(datasetFilePageReqVO.getPageNo());
        pageReqVO.setPageSize(datasetFilePageReqVO.getPageSize());
        pageReqVO.setQualityStatus(datasetFilePageReqVO.getQualityStatus());
        PageResult<DatasetReleaseFileDO> datasetReleaseFilePage = datasetReleaseFileService.getDatasetReleaseFilePage(pageReqVO);
        PageResult<DatasetReleaseFileRespVO> bean = BeanUtils.toBean(datasetReleaseFilePage, DatasetReleaseFileRespVO.class);
        if(CollectionUtils.isNotEmpty(datasetReleaseFilePage.getList())){
            List<DatasetReleaseFileRespVO> voList = BeanUtils.toBean(datasetReleaseFilePage.getList(), DatasetReleaseFileRespVO.class);
            // 查询所有标注文件
            List<Long> fileIdList = datasetReleaseFilePage.getList().stream().map(DatasetReleaseFileDO::getId).collect(Collectors.toList());
            List<DatasetMarkDO> markListByDatasetId = datasetMarkService.getMarkListByOriginalFileIdList(fileIdList);
            List<DatasetMarkRespVO> markRespVOList = BeanUtils.toBean(markListByDatasetId, DatasetMarkRespVO.class);
            if(CollectionUtils.isNotEmpty(markRespVOList)){
                setMarkLabelColor(markRespVOList,dataset);
            }
            // 查询解压原始文件信息
            for (DatasetReleaseFileRespVO respVO : voList) {
                respVO.setOriginalFileUrl(getUrl(request,respVO.getFileUploadPath()));
                respVO.setMarkFileUrl(getUrl(request,respVO.getMarkFileUploadPath()));
                respVO.setQualityStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_file_quality_status, respVO.getQualityStatus()));
                // 设置标注文件信息
                if(CollectionUtils.isNotEmpty(markRespVOList)){
                    respVO.setDatasetMarkList(markRespVOList.stream().filter(mark -> mark.getMarkOriginalFileId().equals(respVO.getId())).collect(Collectors.toList()));
                }
            }
            bean.setList(voList);
        }
        return success(bean);
    }

    @GetMapping("/page")
    @Operation(summary = "获得数据集管理分页")
    @PreAuthorize("@ss.hasPermission('ai:dataset:query')")
    public CommonResult<PageResult<DatasetRespVO>> getDatasetPage(@Valid DatasetPageReqVO pageReqVO,HttpServletRequest request) {
        PageResult<DatasetDO> pageResult = datasetService.getDatasetPage(pageReqVO);
        PageResult<DatasetRespVO> bean = BeanUtils.toBean(pageResult, DatasetRespVO.class);
        if(CollectionUtils.isNotEmpty(bean.getList())){
            // 设置创建者和上传者
            List<Long> creatorList = bean.getList().stream().filter(t -> org.apache.commons.lang3.StringUtils.isNotBlank(t.getCreator()))
                    .map(t -> Long.parseLong(t.getCreator())).collect(Collectors.toList());
            Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(creatorList);
            bean.getList().forEach(vo -> {
                MapUtils.findAndThen(userMap, Long.parseLong(vo.getCreator()),
                        user -> vo.setCreatorName(user.getNickname()));
                MapUtils.findAndThen(userMap, Long.parseLong(vo.getCreator()),
                        user -> vo.setUploderName(user.getNickname()));
            });
            List<Long> ids = bean.getList().stream().map(DatasetRespVO::getId).collect(Collectors.toList());
            Map<Long, DatasetReleaseFileDO> firstFileMap = datasetService.getFirstFileMap(ids);
            for (DatasetRespVO datasetRespVO : bean.getList()) {
                // 设置业务字典
                datasetRespVO.setFileTypeName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_mark_file_type, datasetRespVO.getFileType()));
                datasetRespVO.setSourceTypeName(DictFrameworkUtils.getDictDataLabel(DicConstant.materialLibraryType, datasetRespVO.getSourceType()));
                datasetRespVO.setIndustryName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_Industry_affiliation, datasetRespVO.getIndustryId()));
                datasetRespVO.setIndustry2Name(DictFrameworkUtils.getDictDataLabel(DicConstant.key_model_broad_category, datasetRespVO.getIndustryId2()));
                datasetRespVO.setIndustry3Name(DictFrameworkUtils.getDictDataLabel(DicConstant.key_model_subclass, datasetRespVO.getIndustryId3()));
                datasetRespVO.setSenceTypeName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_mark_biz_type, datasetRespVO.getSenceType()));
                datasetRespVO.setQualityStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_quality_status, datasetRespVO.getQualityStatus()));
                datasetRespVO.setPublishStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_publish_status, datasetRespVO.getPublishStatus()));
                datasetRespVO.setMarkStatusName(DictFrameworkUtils.getDictDataLabel(DicConstant.key_dataset_mark_status, datasetRespVO.getMarkStatus()));
                datasetRespVO.setUrl(getUrl(request,datasetRespVO.getFileUploadPath()));
                DatasetReleaseFileDO datasetReleaseFileDO = firstFileMap.get(datasetRespVO.getId());
                if(null != datasetReleaseFileDO){
                    datasetRespVO.setFirstFileUrl(getUrl(request,datasetReleaseFileDO.getFileUploadPath()));
                }
                try {
                    datasetRespVO.setMarkFileClassesList(JSONArray.parseArray(datasetRespVO.getMarkFileClasses(), String.class));
                    datasetRespVO.setLabelInfoList(JSONArray.parseArray(datasetRespVO.getLabelInfo(), Map.class));
                } catch (Exception e) {
                    //throw new RuntimeException(e);
                }
            }
        }
        return success(bean);
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出数据集管理 Excel")
//    @PreAuthorize("@ss.hasPermission('ai:dataset:export')")
//    @ApiAccessLog(operateType = EXPORT)
//    public void exportDatasetExcel(@Valid DatasetPageReqVO pageReqVO,
//              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<DatasetDO> list = datasetService.getDatasetPage(pageReqVO).getList();
//        // 导出 Excel
//        ExcelUtils.write(response, "数据集管理.xls", "数据", DatasetRespVO.class,
//                        BeanUtils.toBean(list, DatasetRespVO.class));
//    }

    /**
     * 根据相对路径获取可访问的路径
     * @param request
     * @param relativePath
     * @return
     */
    public String getUrl(HttpServletRequest request,String relativePath){
        if(StringUtils.isBlank(relativePath)){
            return null ;
        }
        String scheme = request.getScheme(); // 获取协议（http 或 https）
        String serverName = request.getServerName(); // 获取服务器地址
        int serverPort = request.getServerPort(); // 获取端口号
        String port = serverPort == 80 ? "" : ":" + serverPort;

        relativePath = relativePath.startsWith("/")?relativePath:("/"+relativePath);
        String serverUrl = scheme + "://" + serverName + port;
        return serverUrl+ "/"+materialFilePrePath+relativePath;
    }

}